import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'

// GET /api/customers - 获取所有客户
export async function GET(request: NextRequest) {
    try {
        const { searchParams } = new URL(request.url)
        const includeOrders = searchParams.get('include') === 'orders'

        const customers = await prisma.customer.findMany({
            include: includeOrders ? { orders: true } : undefined,
            orderBy: { created_at: 'desc' }
        })

        return NextResponse.json({
            success: true,
            data: customers
        })
    } catch (error) {
        console.error('Error fetching customers:', error)
        return NextResponse.json(
            { success: false, error: 'Failed to fetch customers' },
            { status: 500 }
        )
    }
}

// POST /api/customers - 创建客户
export async function POST(request: NextRequest) {
    try {
        const body = await request.json()

        const { id, nickname } = body

        // 验证必填字段
        if (!id || !nickname) {
            return NextResponse.json(
                { success: false, error: 'Missing required fields: id and nickname' },
                { status: 400 }
            )
        }

        const customer = await prisma.customer.create({
            data: {
                id,
                nickname
            }
        })

        return NextResponse.json({
            success: true,
            data: customer
        }, { status: 201 })
    } catch (error: any) {
        console.error('Error creating customer:', error)

        // 如果是唯一约束冲突
        if (error.code === 'P2002') {
            return NextResponse.json(
                { success: false, error: 'Customer with this ID already exists' },
                { status: 409 }
            )
        }

        return NextResponse.json(
            { success: false, error: 'Failed to create customer' },
            { status: 500 }
        )
    }
}
